/*
	函数库
*/
var avTemplet 	= AV.Object.extend("Templet");
var fs 			= require('fs');

/**
 * 检测用户是否有管理员权限
 * 2015.04.01  by 胡斌
 * @param page 		当前页码
 * @param pagesize	每页数量
 * @param total		总数量
 */
exports.Paginate = function(page, pagesize, total) {
	var pager={};
	
	pagesize	= parseInt(pagesize);
	page		= parseInt(page);
	if(isNaN(pagesize) || pagesize<1)pagesize=12;
	if(isNaN(page) || page<1)page=1;
	
	pager.firstPage		= 1;
	pager.lastPage		= Math.ceil(total/pagesize);
	pager.currentPage	= page>pager.lastPage?pager.lastPage:page;
	pager.prevPage		= page-1>1?page-1:1;
	pager.nextPage		= page+1<pager.lastPage?page+1:pager.lastPage;
	pager.pagesize		= pagesize;
	pager.total			= total;
	pager.pageArray		= [];
	for(var i=1;i<=pager.lastPage;i++){
		pager.pageArray.push(i);
	}
	
	return pager;
}

/**
 * 前台按模板显示页面
 * 2015.04.08  by 胡斌
 * @param tplFile 用户对象
 * @param res
 */
exports.display = function(res,tplFile,data) {
	var path		= '/tmp/views';
	var fn			= path+"/"+tplFile+".html";
	//console.log("display "+fn);
	
	var showPage	= function(htmlContent,cache){
		var htmlArr		= htmlContent.match(/<!--{=\s*include\s*[a-zA-Z0-9.-]+\s*}-->/g);
		var cssjsArr	= htmlContent.match(/href=["']\/tmp\/views\/[a-zA-Z0-9.-]+["']/g);
		if(htmlArr==null)htmlArr=[];
		if(cssjsArr==null)cssjsArr=[];
		var TempletArr	= htmlArr.concat(cssjsArr);
		
		if(TempletArr.length>0){
			var promise=[],query=[];
			for(var i=0;i<TempletArr.length;i++){
				if(fs.existsSync(path+"/"+TempletArr[i])){
					promise.push(AV.Promise.resolve());
				}else{
					TempletArr[i]	= TempletArr[i].replace(/(<!--{=\s*include\s*)|(\s*}-->)|(href=["']\/tmp\/views\/)|(["'])/g,"");
					var fnArr		= TempletArr[i].split(".");
					query[i]		= new AV.Query(avTemplet);
					
					query[i].equalTo("cacheName", fnArr[0]);
					query[i].equalTo("type", fnArr[1]);
					promise.push(query[i].first());
				}
			}
			AV.Promise.all(promise).then(function (values) {
				var totalHtml="";
				for(var i=0;i<values.length;i++){
					if(typeof(values[i])!="undefined"){
						var filename=path+"/"+values[i].get("cacheName")+"."+values[i].get("type");
						//console.log(filename+" | "+fs.existsSync(filename));
						if(!fs.existsSync(filename)){
							//console.log(filename);
							cache=false;
							fs.writeFileSync(filename,values[i].get("htmlContent"),{mode:0777});
						}
						if(values[i].get("type")=="html"){
							totalHtml+=values[i].get("htmlContent");
						}
					}
				}

				if(totalHtml.length>10){
					showPage(totalHtml,cache);
				}else{
					data.filename=tplFile+"cache";
					data.cache=cache;
					//console.log("cache1:"+data.cache);
					res.render(fn,data);
				}
			});
		}else{
			data.filename=tplFile+"cache";
			data.cache=cache;
			//console.log("cache2:"+data.cache);
			res.render(fn,data);
		}
	}
	
	if(!fs.existsSync(path)){
		fs.mkdirSync(path);
	}
	if(fs.existsSync(fn)){
		//console.log("exist "+fn);
		var htmlContent=fs.readFileSync(fn,'utf-8');
		showPage(htmlContent,false);
	}else{
		var queryTemplet	= new AV.Query(avTemplet);
		queryTemplet.equalTo("cacheName", tplFile);
		queryTemplet.equalTo("type", "html");
		queryTemplet.first().then(function(Templet){
			if(typeof(Templet)!="undefined"){
				var htmlContent=Templet.get("htmlContent");
				//console.log("isnot "+fn);
				//console.log(htmlContent);
				fs.writeFile(fn, htmlContent, function (err) {
					if (err) {
						console.error(err);
						res.render("error",{message:err});
					}else{
						//console.log(fn);
						showPage(htmlContent,false);
					}
				});
			}else{
				console.error("can not find Templet '"+tplFile+"'.");
				res.render("error",{message:"can not find Templet '"+tplFile+".html'."});
			}
		},function(error){
			console.error(error);
			res.render("error",{message:error});
		});
	}
}


/**
 * 后台按模板显示页面
 * 2015.04.17  by 胡斌
 * @param res
 * @param req
 * @param message 错误提示
 */
exports.sentErr = function(res,req,error) {
	if(typeof(error)=="object"){
		error=error.message;
	}
	if(req.body.ajax){
		res.json({error:error});
	}else{
		res.render('/cloud/views/message.html',{
			user:req.AV.user,
			message:error
		});
	}
}

